package com.alibaba.citrus.cr.price.ability.functions.entity.activity;

import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.citrus.cr.price.repository.ActivityQueryRepository;
import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crforecastsales.domian.segmentedactivityterm.dto.LoadListResponse;
import com.epoch.app.crforecastsales.domian.segmentedactivityterm.model.SegmentedActivityTerm;
import com.epoch.app.crplatformenhance.domain.scitemunit.dto.ScItemUnitLoadListRequest;
import com.epoch.app.crplatformenhance.domain.scitemunit.model.ScItemUnit;
import com.epoch.app.crplatformenhance.domain.scitemunit.service.ScItemUnitService;
import com.epoch.app.crpricecenter.dto.response.SegmentedDetailViewResponse;
import com.epoch.app.crpricecenter.sdo.SegmentedActivityTermSDO;
import com.google.common.collect.Maps;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: qiaojiange
 * @create: 2021/10/17
 * @Description 坎级活动实体
 */
@Data
public class SegmentedActivityTermEntity {


    /**
     * 坎级活动SDO
     */
    private SegmentedActivityTermSDO segmentedActivityTermSDO;

    /**
     * 坎级活动组合列表
     */
//    private List<SegmentedActivityCombinationEntity> combinationEntityList;

    /**
     * 活动查询资源库
     */
    private static ActivityQueryRepository activityQueryRepository = SpringContextUtil.getBean(ActivityQueryRepository.class);

    /**
     * 基线接口
     */
    private static BaseDataService baseDataService = SpringContextUtil.getBean(BaseDataService.class);

    /**
     * 销售单位接口
     */
    private static ScItemUnitService service = SpringContextUtil.getBean(ScItemUnitService.class);

    /**
     * 创建坎级活动entity
     * @param segmentedActivityTermSDO
     * @return
     */
    public static SegmentedActivityTermEntity of(SegmentedActivityTermSDO segmentedActivityTermSDO) {
        SegmentedActivityTermEntity segmentedActivityTermEntity = new SegmentedActivityTermEntity();
        segmentedActivityTermEntity.setSegmentedActivityTermSDO(segmentedActivityTermSDO);

        return segmentedActivityTermEntity;
    }

    public Result<List<SegmentedDetailViewResponse>> loadSegmentDetailPageList() {

        LoadListResponse loadListResponse = activityQueryRepository.querySegmentDetailPageList(segmentedActivityTermSDO);
        List loadListResponseResult = loadListResponse.getResult();
        List<SegmentedDetailViewResponse> segmentedDetailViewResponses = Lists.newArrayList();
        Result<List<SegmentedDetailViewResponse>> result = Result.success(segmentedDetailViewResponses);

        if (CollectionUtils.isEmpty(loadListResponseResult)) {
            result.setTotal(0);
            return result;
        }

        List<SegmentedActivityTerm> segmentedActivityTerms = JSONObject.parseArray(JSONObject.toJSONString(loadListResponseResult), SegmentedActivityTerm.class);

        //获取所有的原品编码
        List<String> itemIds = segmentedActivityTerms.stream().filter(item -> StringUtils.isNotBlank(item.getItemId())).map(item -> item.getItemId()).collect(Collectors.toList());

        //获取所有的赠品编码
        List<String> giftIds = segmentedActivityTerms.stream().filter(item -> StringUtils.isNotBlank(item.getGiftId())).map(item -> item.getGiftId()).collect(Collectors.toList());
        //原品+赠品编码list
        List<String> goodsIds = Lists.newArrayList();
        goodsIds.addAll(itemIds);
        goodsIds.addAll(giftIds);
        //获取所有的商品编码，用于查询商品名称
        Map<String, String> itemMap = obtainItemMap(goodsIds);

        //获取所有的销售单位编码
        List<String> salesUnitCodes = segmentedActivityTerms.stream().filter(item->StringUtils.isNotBlank(item.getSalesUnit())).map(x->x.getSalesUnit()).collect(Collectors.toList());
        Map<String, String> saleUnitMap = obtainSaleUnitMap(salesUnitCodes);

        segmentedActivityTerms.stream().forEach(item -> {
            SegmentedDetailViewResponse segmentedDetailViewResponse = new SegmentedDetailViewResponse();
            segmentedDetailViewResponse.setActivitySegmentedId(item.getSegmentedActivityId());
            segmentedDetailViewResponse.setItemName(itemMap.get(item.getItemId()));
            segmentedDetailViewResponse.setItemCount(item.getItemQuantity()+"");
            segmentedDetailViewResponse.setGiftName(itemMap.get(item.getGiftId()));
            segmentedDetailViewResponse.setGiftCount(item.getGiftQuantity()+"");
            segmentedDetailViewResponse.setWithSendNotReUsable(item.getWithSendNotReUsable());
            String specialOfferPrice = item.getSpecialOfferPrice();
            if(StringUtils.isNotBlank(specialOfferPrice)){
                segmentedDetailViewResponse.setSpecialOfferPrice(new BigDecimal(specialOfferPrice.trim()).divide(new BigDecimal(100)).toString());
            }
            //segmentedDetailViewResponse.setSpecialOfferPrice(item.getSpecialOfferPrice());
            segmentedDetailViewResponse.setSalesUnit(saleUnitMap.get(item.getSalesUnit()));
            segmentedDetailViewResponse.setCurrency(item.getCurrency());
            segmentedDetailViewResponses.add(segmentedDetailViewResponse);

        });
        result.setTotal(loadListResponse.getTotal());

        result.setResult(segmentedDetailViewResponses);
        return result;
    }



    private Map<String,String> obtainItemMap(List<String> itemIds){

        //获取内外部物料编码的对应关系（内部编码:外部编码）
        SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
        Map<String, Object> searchReqDTO = new HashMap<>();
        searchReqDTO.put("outerIdList", itemIds);
        searchScItemRequest.setSearchReqDTO(searchReqDTO);

        Map<String, String> itemOutCodeAndDescMap = Maps.newHashMap();
        Result<List<ScItemSDO>> listResult = baseDataService.searchScItem(searchScItemRequest);

        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return Maps.newHashMap();
        }
        itemOutCodeAndDescMap = listResult.getResult().stream().collect(Collectors.toMap(ScItemSDO::getOuterId,ScItemSDO::getTitle));


        return itemOutCodeAndDescMap;

    }
    private Map<String,String> obtainSaleUnitMap(List<String> saleUnitCodes){

        if (CollectionUtils.isEmpty(saleUnitCodes)) {
            return new HashMap<>();
        }
        Map<String, String> map = new HashMap<>();
        for (String code : saleUnitCodes) {
            ScItemUnitLoadListRequest request = new ScItemUnitLoadListRequest();
            request.setOutCode(code);
            Result<List<ScItemUnit>> listResult = service.loadScItemUnitList(request);
            if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                String name = listResult.getResult().get(0).getName();
                map.put(code, name);
            }
        }
        return map;

    }


    /**
     * 获取原品 id
     * @return
     */
    public String obtainItemId() {
        return segmentedActivityTermSDO.getItemId();
    }

    /**
     * 获取原品数量
     *
     * @return
     */
    public Long obtainItemQuantity() {
        return Objects.isNull(segmentedActivityTermSDO.getItemQuantity()) ?
                null : Long.valueOf(segmentedActivityTermSDO.getItemQuantity());
    }

    /**
     * 获取特价
     * @return
     */
    public String obtainSpecialOfferPrice() {
        return Objects.isNull(segmentedActivityTermSDO) ?
                null : segmentedActivityTermSDO.getSpecialOfferPrice();

    }

    /**
     * 获取赠品 ID
     *
     * @return
     */
    public String obtainGiftId() {
        return Objects.isNull(segmentedActivityTermSDO) ?
                null : segmentedActivityTermSDO.getGiftId();
    }

    /**
     * 获取销售单位
     * @return
     */
    public String obtainSalesUnit() {
        return Objects.isNull(segmentedActivityTermSDO) ?
                null : segmentedActivityTermSDO.getSalesUnit();
    }


    /**
     * 获取搭赠坎级不复用标识
     * @return
     */
    public String obtainWithSendNotReUsable() {
        return Objects.isNull(segmentedActivityTermSDO) ?
                null : segmentedActivityTermSDO.getWithSendNotReUsable();
    }

    public Integer obtainGiftQuantity() {
        return Objects.isNull(segmentedActivityTermSDO.getGiftQuantity()) ?
                null : Integer.valueOf(segmentedActivityTermSDO.getGiftQuantity());
    }
}
